/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package econutri.servicos.recordatorio;

import econutri.util.Utils;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lomtools.persistence.GenericDAO;

/**
 *
 * @author Leonardo Oliveira Moreira
 */
public class ListarRecordatorioXMLServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        response.setContentType("application/xml;charset=ISO-8859-1");
        String xml = "";
        String pacienteCodigo = request.getParameter("pacienteCodigo");
        String sql = "SELECT al.codigo, al.descricao, al.carboidrato, al.proteina, al.lipidio, a.refeicaocodigo, a.quantidade, a.data, r.descricao as refeicaodescricao FROM recordatorioitem a, alimento al, refeicao r WHERE a.pacientecodigo = " + pacienteCodigo + " AND a.alimentocodigo = al.codigo AND a.refeicaocodigo = r.codigo ORDER BY a.data, a.refeicaocodigo";
        try {
            GenericDAO dao = new GenericDAO();
            ResultSet rs = dao.executeQuery(sql);
            List<TempRecordatorio> resultList = new ArrayList<TempRecordatorio>();
            while (rs != null && rs.next()) {
                TempRecordatorio tempRecordatorio = new TempRecordatorio();
                tempRecordatorio.setAlimentoCodigo(rs.getInt("codigo"));
                tempRecordatorio.setAlimentoDescricao(rs.getString("descricao"));
                tempRecordatorio.setQuantidade(rs.getDouble("quantidade"));
                tempRecordatorio.setRefeicaoCodigo(rs.getInt("refeicaocodigo"));
                tempRecordatorio.setRefeicaoDescricao(rs.getString("refeicaodescricao"));
                tempRecordatorio.setData(sdf.format(rs.getDate("data")));
                tempRecordatorio.setCarboidrato((rs.getDouble("carboidrato") / 100) * tempRecordatorio.getQuantidade());
                tempRecordatorio.setProteina((rs.getDouble("proteina") / 100) * tempRecordatorio.getQuantidade());
                tempRecordatorio.setLipidio((rs.getDouble("lipidio") / 100) * tempRecordatorio.getQuantidade());
                resultList.add(tempRecordatorio);
            }
            dao.close();
            List<String> dataList = new ArrayList<String>();
            dao = new GenericDAO();
            rs = dao.executeQuery("select r.data from recordatorio r where r.pacientecodigo = " + pacienteCodigo);
            dao.close();
            while (rs != null && rs.next()) {
                dataList.add(sdf.format(rs.getDate("data")));
            }
            xml += "<result>";
            for (String data : dataList) {
                xml += "<recordatorio>";
                xml += "<data>" + data + "</data>";
                List<String> refeicaoList = new ArrayList<String>();
                for (TempRecordatorio t : resultList) {
                    if (t.getData().equals(data) && ! refeicaoList.contains(String.valueOf(t.getRefeicaoCodigo()))) {
                        refeicaoList.add(String.valueOf(t.getRefeicaoCodigo()));
                    }
                }
                xml += "<nutrientes>";
                String sqlNutrientes = "" +
                "select " +
                    "rn.pacientecodigo, " +
                    "rn.data, " +
                    "rn.carboidratomin, " +
                    "rn.proteinamin, " +
                    "rn.lipidiomin, " +
                    "rn.calciomin, " +
                    "rn.fosforomin, " +
                    "rn.ferromin, " +
                    "rn.sodiomin, " +
                    "rn.vitaminaamin, " +
                    "rn.vitaminab1min, " +
                    "rn.vitaminab2min, " +
                    "rn.niacinamin, " +
                    "rn.vitaminacmin, " +
                    "rn.fibramin, " +
                    "rn.colesterolmin, " +
                    "rn.carboidratomax, " +
                    "rn.proteinamax, " +
                    "rn.lipidiomax, " +
                    "rn.calciomax, " +
                    "rn.fosforomax, " +
                    "rn.ferromax, " +
                    "rn.sodiomax, " +
                    "rn.vitaminaamax, " +
                    "rn.vitaminab1max, " +
                    "rn.vitaminab2max, " +
                    "rn.niacinamax, " +
                    "rn.vitaminacmax, " +
                    "rn.fibramax, " +
                    "rn.colesterolmax, " +
                    "(select sum(((a.carboidrato * ri.quantidade)/100)) from recordatorioitem ri, alimento a where ri.pacientecodigo = rn.pacientecodigo and ri.data = rn.data and a.codigo = ri.alimentocodigo) as carboidratocon, " +
                    "(select sum(((a.proteina * ri.quantidade)/100)) from recordatorioitem ri, alimento a where ri.pacientecodigo = rn.pacientecodigo and ri.data = rn.data and a.codigo = ri.alimentocodigo) as proteinacon, " +
                    "(select sum(((a.lipidio * ri.quantidade)/100)) from recordatorioitem ri, alimento a where ri.pacientecodigo = rn.pacientecodigo and ri.data = rn.data and a.codigo = ri.alimentocodigo) as lipidiocon, " +
                    "(select sum(((a.calcio * ri.quantidade)/100)) from recordatorioitem ri, alimento a where ri.pacientecodigo = rn.pacientecodigo and ri.data = rn.data and a.codigo = ri.alimentocodigo) as calciocon, " +
                    "(select sum(((a.fosforo * ri.quantidade)/100)) from recordatorioitem ri, alimento a where ri.pacientecodigo = rn.pacientecodigo and ri.data = rn.data and a.codigo = ri.alimentocodigo) as fosforocon, " +
                    "(select sum(((a.ferro * ri.quantidade)/100)) from recordatorioitem ri, alimento a where ri.pacientecodigo = rn.pacientecodigo and ri.data = rn.data and a.codigo = ri.alimentocodigo) as ferrocon, " +
                    "(select sum(((a.sodio * ri.quantidade)/100)) from recordatorioitem ri, alimento a where ri.pacientecodigo = rn.pacientecodigo and ri.data = rn.data and a.codigo = ri.alimentocodigo) as sodiocon, " +
                    "(select sum(((a.vitaminaa * ri.quantidade)/100)) from recordatorioitem ri, alimento a where ri.pacientecodigo = rn.pacientecodigo and ri.data = rn.data and a.codigo = ri.alimentocodigo) as vitaminaacon, " +
                    "(select sum(((a.vitaminab1 * ri.quantidade)/100)) from recordatorioitem ri, alimento a where ri.pacientecodigo = rn.pacientecodigo and ri.data = rn.data and a.codigo = ri.alimentocodigo) as vitaminab1con, " +
                    "(select sum(((a.vitaminab2 * ri.quantidade)/100)) from recordatorioitem ri, alimento a where ri.pacientecodigo = rn.pacientecodigo and ri.data = rn.data and a.codigo = ri.alimentocodigo) as vitaminab2con, " +
                    "(select sum(((a.niacina * ri.quantidade)/100)) from recordatorioitem ri, alimento a where ri.pacientecodigo = rn.pacientecodigo and ri.data = rn.data and a.codigo = ri.alimentocodigo) as niacinacon, " +
                    "(select sum(((a.vitaminac * ri.quantidade)/100)) from recordatorioitem ri, alimento a where ri.pacientecodigo = rn.pacientecodigo and ri.data = rn.data and a.codigo = ri.alimentocodigo) as vitaminaccon, " +
                    "(select sum(((a.fibra * ri.quantidade)/100)) from recordatorioitem ri, alimento a where ri.pacientecodigo = rn.pacientecodigo and ri.data = rn.data and a.codigo = ri.alimentocodigo) as fibracon, " +
                    "(select sum(((a.colesterol * ri.quantidade)/100)) from recordatorioitem ri, alimento a where ri.pacientecodigo = rn.pacientecodigo and ri.data = rn.data and a.codigo = ri.alimentocodigo) as colesterolcon " +
                "from recordatorionutriente rn " +
                "where rn.pacientecodigo = " + pacienteCodigo + " and rn.data = '" + Utils.converterDataSQL(data) + "'" +
                        "";
                dao = new GenericDAO();
                ResultSet rsNutrientes = dao.executeQuery(sqlNutrientes);
                dao.close();
                while (rsNutrientes != null && rsNutrientes.next()) {
                    xml += "<carboidratomin>" + rsNutrientes.getDouble("carboidratomin") + "</carboidratomin>";
                    xml += "<proteinamin>" + rsNutrientes.getDouble("proteinamin") + "</proteinamin>";
                    xml += "<lipidiomin>" + rsNutrientes.getDouble("lipidiomin") + "</lipidiomin>";
                    xml += "<calciomin>" + rsNutrientes.getDouble("calciomin") + "</calciomin>";
                    xml += "<fosforomin>" + rsNutrientes.getDouble("fosforomin") + "</fosforomin>";
                    xml += "<ferromin>" + rsNutrientes.getDouble("ferromin") + "</ferromin>";
                    xml += "<sodiomin>" + rsNutrientes.getDouble("sodiomin") + "</sodiomin>";
                    xml += "<vitaminaamin>" + rsNutrientes.getDouble("vitaminaamin") + "</vitaminaamin>";
                    xml += "<vitaminab1min>" + rsNutrientes.getDouble("vitaminab1min") + "</vitaminab1min>";
                    xml += "<vitaminab2min>" + rsNutrientes.getDouble("vitaminab2min") + "</vitaminab2min>";
                    xml += "<niacinamin>" + rsNutrientes.getDouble("niacinamin") + "</niacinamin>";
                    xml += "<vitaminacmin>" + rsNutrientes.getDouble("vitaminacmin") + "</vitaminacmin>";
                    xml += "<fibramin>" + rsNutrientes.getDouble("fibramin") + "</fibramin>";
                    xml += "<colesterolmin>" + rsNutrientes.getDouble("colesterolmin") + "</colesterolmin>";
                    xml += "<carboidratomax>" + rsNutrientes.getDouble("carboidratomax") + "</carboidratomax>";
                    xml += "<proteinamax>" + rsNutrientes.getDouble("proteinamax") + "</proteinamax>";
                    xml += "<lipidiomax>" + rsNutrientes.getDouble("lipidiomax") + "</lipidiomax>";
                    xml += "<calciomax>" + rsNutrientes.getDouble("calciomax") + "</calciomax>";
                    xml += "<fosforomax>" + rsNutrientes.getDouble("fosforomax") + "</fosforomax>";
                    xml += "<ferromax>" + rsNutrientes.getDouble("ferromax") + "</ferromax>";
                    xml += "<sodiomax>" + rsNutrientes.getDouble("sodiomax") + "</sodiomax>";
                    xml += "<vitaminaamax>" + rsNutrientes.getDouble("vitaminaamax") + "</vitaminaamax>";
                    xml += "<vitaminab1max>" + rsNutrientes.getDouble("vitaminab1max") + "</vitaminab1max>";
                    xml += "<vitaminab2max>" + rsNutrientes.getDouble("vitaminab2max") + "</vitaminab2max>";
                    xml += "<niacinamax>" + rsNutrientes.getDouble("niacinamax") + "</niacinamax>";
                    xml += "<vitaminacmax>" + rsNutrientes.getDouble("vitaminacmax") + "</vitaminacmax>";
                    xml += "<fibramax>" + rsNutrientes.getDouble("fibramax") + "</fibramax>";
                    xml += "<colesterolmax>" + rsNutrientes.getDouble("colesterolmax") + "</colesterolmax>";
                    xml += "<carboidratocon>" + rsNutrientes.getDouble("carboidratocon") + "</carboidratocon>";
                    xml += "<proteinacon>" + rsNutrientes.getDouble("proteinacon") + "</proteinacon>";
                    xml += "<lipidiocon>" + rsNutrientes.getDouble("lipidiocon") + "</lipidiocon>";
                    xml += "<calciocon>" + rsNutrientes.getDouble("calciocon") + "</calciocon>";
                    xml += "<fosforocon>" + rsNutrientes.getDouble("fosforocon") + "</fosforocon>";
                    xml += "<ferrocon>" + rsNutrientes.getDouble("ferrocon") + "</ferrocon>";
                    xml += "<sodiocon>" + rsNutrientes.getDouble("sodiocon") + "</sodiocon>";
                    xml += "<vitaminaacon>" + rsNutrientes.getDouble("vitaminaacon") + "</vitaminaacon>";
                    xml += "<vitaminab1con>" + rsNutrientes.getDouble("vitaminab1con") + "</vitaminab1con>";
                    xml += "<vitaminab2con>" + rsNutrientes.getDouble("vitaminab2con") + "</vitaminab2con>";
                    xml += "<niacinacon>" + rsNutrientes.getDouble("niacinacon") + "</niacinacon>";
                    xml += "<vitaminaccon>" + rsNutrientes.getDouble("vitaminaccon") + "</vitaminaccon>";
                    xml += "<fibracon>" + rsNutrientes.getDouble("fibracon") + "</fibracon>";
                    xml += "<colesterolcon>" + rsNutrientes.getDouble("colesterolcon") + "</colesterolcon>";
                }
                xml += "</nutrientes>";
                double calorias = 0;
                for (String r : refeicaoList) {
                    xml += "<refeicao>";
                    xml += "<refeicaocodigo>" + r + "</refeicaocodigo>";
                    for (TempRecordatorio t : resultList) {
                        if (t.getData().equals(data) && t.getRefeicaoCodigo() == Integer.parseInt(r)) {
                            xml += "<refeicaodescricao>" + t.getRefeicaoDescricao() + "</refeicaodescricao>";
                            break;
                        }
                    }
                    xml += "<itens>";
                    for (TempRecordatorio t : resultList) {
                        if (t.getData().equals(data) && t.getRefeicaoCodigo() == Integer.parseInt(r)) {
                            xml += "<item>";
                                xml += "<codigo>" + t.getAlimentoCodigo() + "</codigo>";
                                xml += "<descricao>" + t.getAlimentoDescricao() + "</descricao>";
                                xml += "<quantidade>" + t.getQuantidade() + "</quantidade>";
                                calorias += (Utils.getCalorias(t.getQuantidade(), t.getCarboidrato(), t.getProteina(), t.getLipidio()));
                            xml += "</item>";
                        }
                    }
                    xml += "</itens>";
                    xml += "</refeicao>";
                }
                xml += "<calorias>" + Utils.formatDoubleValue(calorias) + "</calorias>";
                xml += "</recordatorio>";
            }
        } catch (SQLException ex) {

        }
        xml += "</result>";
        PrintWriter out = response.getWriter();
        try {
            out.println(xml);
        } finally {
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}